package com.yangchoi.jetpackcompose.ui.widget.component

import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.ColorFilter
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.constraintlayout.compose.ConstraintLayout
import com.yangchoi.jetpackcompose.R
import com.yangchoi.jetpackcompose.ui.widget.ext.onClick

val AppBarHeight = 48.dp

@Composable
fun CommonTopBar(
    title:String,
    titleStyle: TextStyle = TextStyle(fontSize = 16.sp, color = Color.Black, fontWeight = FontWeight.Bold),
    showBackIcon: Boolean = true,
    onBackClick: (()->Unit)? = null,
    backIconColor: Color = Color.Black,
    rightContent: @Composable (()->Unit)? = null,
    bgColor: Color = Color.White,
    showLine: Boolean = true,
    lineColor: Color = Color.Gray.copy(alpha = 0.5f)
){
    ConstraintLayout(modifier = Modifier
        .fillMaxWidth()
        .height(AppBarHeight)
        .background(color = bgColor)
    ) {
        val (content,line) = createRefs()

        Box(modifier = Modifier.fillMaxSize()){
            if (showBackIcon){
                Image(painter = painterResource(id = R.mipmap.icon_back),
                    contentDescription = null,
                    modifier = Modifier
                        .padding(start = 12.dp)
                        .size(20.dp)
                        .onClick {
                            onBackClick?.invoke()
                        }
                        .align(Alignment.CenterStart),
                    colorFilter = ColorFilter.tint(color = backIconColor)
                )
            }

            Text(text = title, style = titleStyle, modifier = Modifier.align(Alignment.Center))

            if (rightContent != null){
                Box(modifier = Modifier.padding(end = 12.dp).align(Alignment.CenterEnd)){
                    rightContent()
                }
            }
        }

        if (showLine){
            Box(modifier = Modifier.constrainAs(line) {
                bottom.linkTo(parent.bottom)
            }){
                DefaultLine(bgColor = lineColor)
            }
        }
    }
}